using System;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
using Microsoft.Win32;
using Microsoft.VisualBasic;



namespace DotNetControl
{
    #region EventHandlers Delegates
    //For more information on why some of this is necessary to get events to fire
    //http://support.microsoft.com/default.aspx?scid=kb;en-us;313891
    [ComVisible(false)]
    public delegate void toolbarButtonClickEventHandler();
     [ComVisible(false)]
    public delegate void toolbarPosChangedEventHandler();

     #endregion

    #region ControlEvents Interface
    [GuidAttribute("F11EC17C-59E1-42D1-AE96-712AB79F20AB")]
    [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
    public interface ControlEvents
    {
        [DispIdAttribute(1)]
        void toolbarbuttonClick();
        [DispIdAttribute(2)]
        void ToolBarPosChanged();
    }
    #endregion

    #region DotNetToolbar Class
    [Guid("2DEFE6F9-6738-454C-BEF1-CF944E7F5F06")]
    [ProgId("DotNetControl.DotNetToolbar")]
    [ClassInterface(ClassInterfaceType.AutoDual), ComSourceInterfaces(typeof(ControlEvents))]
    public partial class DotNetToolbar : UserControl
    {
        private String ButtonKey;

        public DotNetToolbar()
        {
            ButtonKey = "";
            InitializeComponent();
            
            // Assign unique tag key for each buttons
            New.Tag   = "TOOL_STANDARD_NEW";
            Open.Tag  = "TOOL_STANDARD_OPEN";
            Save.Tag  = "TOOL_STANDARD_SAVE";
            print.Tag = "TOOL_STANDARD_PRINT";

            Cut.Tag  = "TOOL_STANDARD_CUT";
            copy.Tag = "TOOL_STANDARD_COPY";
            paste.Tag = "TOOL_STANDARD_PASTE";

            Undo.Tag = "TOOL_STANDARD_UNDO";
            Redo.Tag = "TOOL_STANDARD_REDO";

            Run.Tag = "TOOL_STANDARD_RUN";

            SoltnExplrer.Tag = "TOOL_STANDARD_SOLEXPLR";
            DocView.Tag      = "TOOL_STANDARD_DOCVIEW";
            ToolBox.Tag      = "TOOL_STANDARD_TOOLBOX";
            ClassBrowser.Tag = "TOOL_STANDARD_CLSBROWSR";
            Properties.Tag   = "TOOL_STANDARD_PROPERTIES";
            Help.Tag         = "TOOL_STANDARD_HELP";
            ObjectBrowser.Tag = "TOOL_STANDARD_OBJBROWSR";

            //AlignLeft.Tag    = "TOOL_LAYOUT_LEFTS";
            //AlignCenters.Tag = "TOOL_LAYOUT_CENTERS";
            //AlignTops.Tag    = "TOOL_LAYOUT_TOPS";
            //AlignRight.Tag   = "TOOL_LAYOUT_RIGHTS";
            //AlignBottoms.Tag = "TOOL_LAYOUT_BOTTOMS";
            //AlignMiddles.Tag = "TOOL_LAYOUT_MIDDLES";
            //CenterHorrizontly.Tag = "TOOL_LAYOUT_VERTICALLY";
            //CenterVertically.Tag  = "TOOL_LAYOUT_HORIZONTALLY";

            //SameWidth.Tag    = "TOOL_LAYOUT_WIDTHS";
            //SameHeight.Tag   = "TOOL_LAYOUT_HEIGHTS";
            //SameSize.Tag     = "TOOL_LAYOUT_SIZES";
            //BringFront.Tag = "TOOL_LAYOUT_BRINGFRONT";
            //SendBack.Tag   = "TOOL_LAYOUT_SENDBACK";
            //TabOrders.Tag    = "TOOL_LAYOUT_TABORDERS";

            //this.setButtonEnable("TOOL_LAYOUT_*", false);

        }

        #region
        public event DotNetControl.toolbarButtonClickEventHandler toolbarButtonClick;
        public event DotNetControl.toolbarPosChangedEventHandler ToolBarPosChanged;
        #endregion
        
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                    components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region COM Registration
        //For more information on why the following two functions are necessary
        //http://www.codeproject.com/cs/miscctrl/exposingdotnetcontrols.asp
        //copyright Morgan Skinner, 2001
        [ComRegisterFunction()]
        public static void RegisterClass(string key)
        {
            // Strip off HKEY_CLASSES_ROOT\ from the passed key as I don't need it
            StringBuilder sb = new StringBuilder(key);
            sb.Replace(@"HKEY_CLASSES_ROOT\", "");

            // Open the CLSID\{guid} key for write access
            RegistryKey k = Registry.ClassesRoot.OpenSubKey(sb.ToString(), true);

            // And create the 'Control' key - this allows it to show up in 
            // the ActiveX control container 
            RegistryKey ctrl = k.CreateSubKey("Control");
            ctrl.Close();

            // Next create the CodeBase entry - needed if not string named and GACced.
            RegistryKey inprocServer32 = k.OpenSubKey("InprocServer32", true);
            inprocServer32.SetValue("CodeBase", Assembly.GetExecutingAssembly().CodeBase);
            inprocServer32.Close();

            // Finally close the main key
            k.Close();
        }

        [ComUnregisterFunction()]
        public static void UnregisterClass ( string key )
        {
          StringBuilder sb = new StringBuilder ( key ) ;
          sb.Replace(@"HKEY_CLASSES_ROOT\","") ;

          // Open HKCR\CLSID\{guid} for write access
          RegistryKey k = Registry.ClassesRoot.OpenSubKey(sb.ToString(),true);

          // Delete the 'Control' key, but don't throw an exception if it does not exist
          k.DeleteSubKey ( "Control" , false ) ;

          // Next open up InprocServer32
          RegistryKey inprocServer32 = k.OpenSubKey ( "InprocServer32" , true ) ;

          // And delete the CodeBase key, again not throwing if missing 
          k.DeleteSubKey ( "CodeBase" , false ) ;

          // Finally close the main key 
          k.Close ( ) ;
        }
        #endregion
        
        #region Toolbar Clicks
        public string GetLastPressedButton()
        {
            return ButtonKey;
        }
        
        private void onButtonClick(object sender, EventArgs e)
        {
            ToolStripButton obj = (ToolStripButton)sender;

            ButtonKey = obj.Tag.ToString() ;
            toolbarButtonClick();
        }
        
        #endregion
        
        private ToolStrip FindToolBar(string ToolBarID)
        {
            ToolStrip ToolBarObject = null;

            ToolBarID = ToolBarID.ToUpper().Trim();
            switch (ToolBarID)
            {
                case "TOOL_STANDARD":
                    //Standard toolbar
                    ToolBarObject = StandardToolBar;
                    break;

                //case "TOOL_LAYOUT":
                //    //Layout toolbar
                //    ToolBarObject = LayoutToolbar;
                //    break;

                default:
                    break;
            }

            return ToolBarObject;
        }
        
        public void setToolbarVisible(string ToolBar, bool Visible)
        {
            ToolStrip ToolBarObject = FindToolBar(ToolBar);

            if (ToolBarObject != null)
            {
                ToolBarObject.Visible = Visible;
            }
        }
        
        public bool getToolbarVisible(string ToolBar)
        {
            ToolStrip ToolBarObject = FindToolBar(ToolBar);
            bool ToolBarVisible = false;

            if (ToolBarObject != null)
            {
                ToolBarVisible = ToolBarObject.Visible;
            }

            return ToolBarVisible;
        }
        
        public bool setButtonEnable(string ItemKey, bool ItemEnabled)
        { 
            bool ItemFound = false ;
            ItemKey = ItemKey.ToUpper().Trim();
            
            int ChrPos = ItemKey.LastIndexOf("_");
            if (ChrPos > 0)
            {
                string ToolBarName = ItemKey.Substring(0, ChrPos);             
                ToolStrip ToolbarObj = FindToolBar(ToolBarName);

                if (ToolbarObj != null)
                {
                    //Search for item in temp collection
                    for (int itemindx = 0; itemindx <= ToolbarObj.Items.Count; itemindx++)
                    {
                        if (ToolbarObj.Items[itemindx].Tag != null)
                        {
                            string ButtonTag = ToolbarObj.Items[itemindx].Tag.ToString();
                             if (ButtonTag.Length > 0 && ButtonTag == ItemKey)
                             {
                                 //Set Item Enable property
                                 ToolbarObj.Items[itemindx].Enabled = ItemEnabled;
                                 ItemFound = true;
                                 break;
                              }
                    }
                    }
                }
            }

            return ItemFound;
        }

        public int getToolbarContainerAreaHeight()
        {
            int maxArea = 0;
            
            // Standard toolbar
            ToolStrip LastToolStrip = this.StandardToolBar;

            ////Layout toolbar
            //if (LastToolStrip.Top < this.LayoutToolbar.Top)
            //{
            //    LastToolStrip = this.LayoutToolbar;
            //}

            maxArea = LastToolStrip.Top + LastToolStrip.Height;

            return maxArea;
        }
        
        private void StandardToolBar_LocationChanged(object sender, EventArgs e)
        {
            //if (ToolBarPosChanged != null)
            //{
            //    ToolBarPosChanged();
            //}
        }

        private void LayoutToolbar_LocationChanged(object sender, EventArgs e)
        {
            ////MessageBox.Show("2");
            //if (ToolBarPosChanged != null)
            //{
            //    ToolBarPosChanged();
            //}
        }

        private void StandardToolBar_EndDrag(object sender, EventArgs e)
        {
            if (ToolBarPosChanged != null)
            {
                ToolBarPosChanged();
            }   
        }

                      
    
    }
    #endregion
}